﻿using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Devonline.Core;

/// <summary>
/// 自定义时间格式化器
/// </summary>
public class DateTimeConverter : JsonConverter<DateTime>
{
    private readonly string _formatter;
    public DateTimeConverter(string formatter)
    {
        _formatter = formatter;
    }

    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (!reader.TryGetDateTime(out DateTime value) && DateTime.TryParseExact(reader.GetString(), _formatter, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out DateTime dateTimeValue))
        {
            return dateTimeValue;
        }

        return value;
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString(_formatter, CultureInfo.CurrentCulture));
    }
}

/// <summary>
/// 自定义时间格式化器
/// </summary>
public class DateTimeOffsetConverter : JsonConverter<DateTimeOffset>
{
    private readonly string _formatter;
    public DateTimeOffsetConverter(string formatter)
    {
        _formatter = formatter;
    }

    public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (!reader.TryGetDateTime(out DateTime value) && DateTimeOffset.TryParseExact(reader.GetString(), _formatter, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out DateTimeOffset dateTimeValue))
        {
            return dateTimeValue;
        }

        return value;
    }

    public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString(_formatter, CultureInfo.CurrentCulture));
    }
}